package org.jeecg.modules.util.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.util.DbBackupInfo;
import org.jeecg.modules.util.entity.TigerDataBackup;
import org.jeecg.modules.util.entity.TigerDataBackupTables;
import org.jeecg.modules.util.service.ITigerDataBackupService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.util.service.ITigerDataBackupTablesService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 数据库备份
 * @Author: jeecg-boot
 * @Date:   2022-07-22
 * @Version: V1.0
 */
@Api(tags="数据库备份")
@RestController
@RequestMapping("/util/tigerDataBackup")
@Slf4j
public class TigerDataBackupController extends JeecgController<TigerDataBackup, ITigerDataBackupService> {
	@Autowired
	private ITigerDataBackupService tigerDataBackupService;

	@Autowired
	private ITigerDataBackupTablesService tigerDataBackupTablesService;

	@Autowired
	private DbBackupInfo dbBackupInfo;
	/**
	 * 分页列表查询
	 *
	 * @param tigerDataBackup
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "数据库备份-分页列表查询")
	@ApiOperation(value="数据库备份-分页列表查询", notes="数据库备份-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TigerDataBackup>> queryPageList(TigerDataBackup tigerDataBackup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TigerDataBackup> queryWrapper = QueryGenerator.initQueryWrapper(tigerDataBackup, req.getParameterMap());
		Page<TigerDataBackup> page = new Page<TigerDataBackup>(pageNo, pageSize);
		IPage<TigerDataBackup> pageList = tigerDataBackupService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   数据库备份-添加
	 *
	 * @param tigerDataBackup
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TigerDataBackup tigerDataBackup) {
		try {
			boolean isReady = tigerDataBackupService.getReady();
			if (isReady) {
				//Get backup tables;
				Map<String,Object> mapQuery = new HashMap<>();
				mapQuery.put("isback","1");
				List<TigerDataBackupTables> tables = tigerDataBackupTablesService.listByMap(mapQuery);

				//Create record;
				String tableNames = dbBackupInfo.getTabelNames(tables);
				if(tableNames == null) throw new Exception("没有可备份的表");
				final TigerDataBackup backup = new TigerDataBackup();
				dbBackupInfo.generateDbScripts(backup, tableNames);
				dbBackupInfo.recoverScript(backup);
				backup.setDumpTime(Calendar.getInstance().getTime());
				backup.setRunStatus("1");
				tigerDataBackupService.save(backup);

				//Run backup And update Status;
				new Thread(){
					@Override
					public void run() {
						super.run();
						try {
							dbBackupInfo.runScript(backup.getDumpCmd());
							Thread.sleep(2000);
							File file = new File(backup.getBackFile());
							//Backup Finish
							if(file.exists()) {
								DecimalFormat df = new DecimalFormat("#0.00");
								backup.setFileSize(df.format(file.length()/124.0) + "K");
							}else{
								backup.setFileSize("-1");
							}
							backup.setRunStatus("0");
						}catch (Exception eRun){
							//Backup Fail
							backup.setRemark(eRun.getMessage());
							backup.setRunStatus("0");
						}
						tigerDataBackupService.saveOrUpdate(backup);
					}
				}.start();
			}
			return Result.OK("启动成功！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.OK("启动失败！"+e.getMessage());
		}
	}
	
	/**
	 *  编辑
	 *
	 * @param tigerDataBackup
	 * @return
	 */
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TigerDataBackup tigerDataBackup) {
		tigerDataBackupService.updateById(tigerDataBackup);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  数据库备份-还原
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="数据库备份还原")
	 @GetMapping(value = "/recover")
	 public Result<String> recover(@RequestParam(name="recordId",required=true) String id) {
	 	try{
			boolean isReady = tigerDataBackupService.getReady();
			if(isReady){
				final TigerDataBackup bku = tigerDataBackupService.getById(id);
				bku.setRunStatus("3");
				tigerDataBackupService.updateById(bku);
				new Thread(){
					@Override
					public void run() {
						super.run();
						try {
							dbBackupInfo.runScript(bku.getRecoverCmd());
							bku.setRecoverTime(Calendar.getInstance().getTime());
							bku.setOperateCount(bku.getOperateCount()==null?1:bku.getOperateCount()+1);
						}catch (Exception eRun){
							eRun.printStackTrace();
							bku.setRemark(eRun.getMessage());
						}
						bku.setRunStatus("0");
						tigerDataBackupService.updateById(bku);
					}
				}.start();
			}
			return Result.OK("启动成功!");
		}catch (Exception e){
			return Result.OK("启动失败!");
		}
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "数据库备份-通过id删除")
	@ApiOperation(value="数据库备份-通过id删除", notes="数据库备份-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		try{
			TigerDataBackup db = tigerDataBackupService.getById(id);
			deleteFile(db.getBackFile());
			tigerDataBackupService.removeById(id);
			return Result.OK("删除成功!");
		}catch (Exception e){
			return Result.OK("删除失败!"+e.getMessage());
		}

	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "数据库备份-批量删除")
	@ApiOperation(value="数据库备份-批量删除", notes="数据库备份-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		try{
			List<String> list = Arrays.asList(ids.split(","));
			list.stream().forEach(l->{
				TigerDataBackup bku = this.tigerDataBackupService.getById(l);
				if(deleteFile(bku.getBackFile())){
					this.tigerDataBackupService.removeById(l);
				}
			});
			return Result.OK("批量删除成功!");
		}catch (Exception e){
			return Result.OK("批量删除部分失败!");
		}
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "数据库备份-通过id查询")
	@ApiOperation(value="数据库备份-通过id查询", notes="数据库备份-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TigerDataBackup> queryById(@RequestParam(name="id",required=true) String id) {
		TigerDataBackup tigerDataBackup = tigerDataBackupService.getById(id);
		if(tigerDataBackup==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(tigerDataBackup);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tigerDataBackup
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TigerDataBackup tigerDataBackup) {
        return super.exportXls(request, tigerDataBackup, TigerDataBackup.class, "数据库备份");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TigerDataBackup.class);
    }

    private boolean deleteFile(String path){
		File file = new File(path);
		if(file.exists()){
			return file.delete();
		}
		return false;
	}
}
